<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\admin\service\AliOosService;
use app\admin\service\LocationService;
use app\admin\service\ResourceCateService;
use app\admin\service\ResourceCheckService;
use app\admin\service\ResourcePathService;
use app\admin\service\ResourceRecommendService;
use app\admin\service\ResourceService;
use app\admin\service\UsersService;
use app\admin\validate\Resource as ResourceValidate;
use app\AdminController;
use app\index\controller\TimedTask;
use think\exception\ValidateException;

/**
 * 社群
 * Class Resource
 * @package app\admin\controller
 */
class Resource extends AdminController
{
    /**
     * 社群列表
     * @param array $otherWheres
     * @param int $other
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($otherWheres = [], $other = 0)
    {
        $type = intval($this->request->param('type', 1));
        if (request()->isPost()) {
            $where = [];
            // 关键词搜索
            $keywords = $this->request->param('keywords', '');
            if ($keywords) {
                $where[] = ['r.name|r.company|l.name|c.name', 'like', '%' . $keywords . '%'];
            }

            switch ($other) {
                case 1:
                    $order = ['r.sort' => 'desc', 'r.create_time' => 'desc'];
                    break;
                case 2:
                    $order = ['r.sort1' => 'desc', 'r.create_time' => 'desc'];
                    break;
                case 3:
                    $order = ['re.show_time' => 'desc', 'r.create_time' => 'desc'];
                    break;
                default:
                    $order = ['r.create_time' => 'desc'];
            }

            $where1 = [
                'order' => $order,
                'otherWheres' => $otherWheres
            ];

            // 推荐列表
            if ($other == 3) {
                $list = ResourceService::getRecommendList($where, $where1, $this->page, $this->pagesize);
                $count = ResourceService::countRecommendList($where);
            } else {
                $list = ResourceService::getResourceList($where, $where1, $this->page, $this->pagesize);
                $count = ResourceService::countResourceList($where, $where1);
            }

            return adminResponseJson(['type' => $type, 'list' => $list, 'count' => $count]);
        }

        // 当日新增
        $todayResource = ResourceService::todayResource();
        // 本周新增
        $countResourceWeek = ResourceService::countResourceWeek();
        // 总社群
        $countResource = ResourceService::countResource();
        // 当月新增
        $countResourceMonth = ResourceService::countResourceMonth();
        // 当月社群（折线图）
        $resourceMonthLine = ResourceService::getResourceMonthLine();
        // 审核中
        $resourceCheck = ResourceCheckService::countResourceCheck(['status' => 0]);
        // 已通过
        $resourcePass = ResourceCheckService::countResourceCheck(['status' => 1]);
        // 被驳回
        $resourceReject = ResourceCheckService::countResourceCheck(['status' => 2]);

        return view('', [
            'type' => $type,
            'resource_data' => [
                'todayResource' => $todayResource,
                'countResource' => $countResource,
                'countResourceWeek' => $countResourceWeek,
                'countResourceMonth' => $countResourceMonth,
                'resourceMonthLine' => $resourceMonthLine,
            ],
            'check_data' => [
                'resourceCheck' => $resourceCheck,
                'resourceLastCheck' => $countResource - $resourceCheck,
                'resourceCheckScale' => round(($resourceCheck / $countResource) * 100, 2) . '%',
                'resourcePass' => $resourcePass,
                'resourceLastPass' => $countResource - $resourcePass,
                'resourcePassScale' => round(($resourcePass / $countResource) * 100, 2) . '%',
                'resourceReject' => $resourceReject,
                'resourceLastReject' => $countResource - $resourceReject,
                'resourceRejectScale' => round(($resourceReject / $countResource) * 100, 2) . '%',
            ]
        ]);
    }

    /**
     * 社群添加
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourceAdd()
    {
        if (request()->isPost()) {
            $data = $this->request->post();

            try {
                validate(ResourceValidate::class)->resourceInsert()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (intval($data['uid']) < 1) {
                $this->error(adminJsonMsg(1006));
            }

            // 根据用户id查询是否存在此人
            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10010));
            }


            // 获取社群编号
            $data['number'] = getResourceNumber($data['uid']);
            $res = ResourceService::createResource($data);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $imageArr = $data['images'] ? explode(',', $data['images']) : [];

            if ($imageArr) {
                // 存储图片/视频路径到指定表
                foreach ($imageArr as $type => $path) {
                    ResourcePathService::createResourcePath([
                        'path' => $path,
                        'type' => 1,
                        'rid' => $res->id,
                    ]);
                }
            }

            $imageArr[] = $data['qrcode'];
            if ($data['logo']) {
                $imageArr[] = $data['logo'];
            }

            AliOosService::uploadAliOos($imageArr);

            $this->success(adminJsonMsg(1004), (STRING)url('/resource/index'));
        }

        // 二级分类
        $resourceCate = ResourceCateService::getResourceCate();
        // 省份
        $province = LocationService::getProvince();
        return view('', ['resourceCate' => $resourceCate, 'province' => $province]);
    }

    /**
     * 社群编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourceEdit()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = ResourceService::findResource(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }
        $info['yqrcode'] = $info['qrcode'] ? config('url.url') . $info['qrcode'] : '';
        $info['ylogo'] = $info['logo'] ? config('url.url') . $info['logo'] : '';

        // 格式化图片和视频
        $path_list = ResourcePathService::getResourcePath(['rid' => $info['id']]);
        $info['images_list'] = '';
        $info['images_path'] = '';
        $yImagesArr = [];
        if ($path_list) {
            $path = '';
            $images_path = '';
            foreach ($path_list as $v) {
                $path .= config('url.url') . $v['path'] . ',';
                $images_path .= $v['path'] . ',';
                $yImagesArr[] = $v['path'];
            }
            $info['images_list'] = rtrim($path, ',');
            $info['images_path'] = rtrim($images_path, ',');
        }

        if (request()->isPost()) {
            $data = $this->request->post();

            try {
                validate(ResourceValidate::class)->resourceEdit()->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            if (intval($data['uid']) < 1) {
                $this->error(adminJsonMsg(1006));
            }

            // 根据用户id查询是否存在此人
            $users = UsersService::findUsers(['id' => $data['uid']]);
            if (!$users) {
                $this->error(adminJsonMsg(10010));
            }

            // 获取社群编号
            if ($data['uid'] != $info['uid']) {
                $data['number'] = getResourceNumber($data['uid']);
            }
            $res = ResourceService::updateResource($data, ['id' => $data['id']]);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $pathArr = [];
            $addArr = [];

            // 更改了logo
            if ($data['logo'] != $info['logo']) {
                if ($info['logo']) {
                    $pathArr[] = $info['logo'];
                }
                if ($data['logo']) {
                    $addArr[] = $data['logo'];
                }
            }

            // 更改了二维码
            if ($data['qrcode'] != $info['qrcode']) {
                $pathArr[] = $info['qrcode'];
                $addArr[] = $data['qrcode'];
            }

            $imageArr = $data['images'] ? explode(',', $data['images']) : [];

            // 比对是否新增了封面图片
            $savePathArr = array_diff($imageArr, $yImagesArr);

            if ($savePathArr) {
                // 存储图片/视频路径到指定表
                foreach ($savePathArr as $type => $path) {
                    ResourcePathService::createResourcePath([
                        'path' => $path,
                        'type' => 1,
                        'rid' => $data['id'],
                    ]);
                }

                AliOosService::uploadAliOos($savePathArr);
            }

            AliOosService::uploadAliOos($addArr);


            // 比对是否删除了封面图片
            $delPathArr = array_diff($yImagesArr, $imageArr);

            // 删除图片/视频所在表位置
            if ($delPathArr) {
                foreach ($delPathArr as $paths) {
                    ResourcePathService::delResourcePath(['rid' => $data['id'], 'path' => $paths]);
                }
            }

            $this->success(adminJsonMsg(1004), (STRING)url('/resource/index'));
        }

        // 二级分类
        $resourceCate = ResourceCateService::getResourceCate();
        // 省份
        $province = LocationService::getProvince();
        // 城市
        $city = LocationService::getCity($info['province']);
        // 地区
        $area = LocationService::getArea($info['city']);
        return view('', [
            'info' => $info,
            'resourceCate' => $resourceCate,
            'province' => $province,
            'city' => $city,
            'area' => $area,
        ]);
    }

    /**
     * 社群详情
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resourceShow()
    {
        $id = intval($this->request->param('id', 0));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }

        $info = ResourceService::findResource(['id' => $id]);
        if (!$info) {
            $this->error(adminJsonMsg(1002));
        }
        $info['qrcode'] = $info['qrcode'] ? config('url.url') . $info['qrcode'] : '';
        $info['logo'] = $info['logo'] ? config('url.url') . $info['logo'] : '';

        // 格式化图片和视频
        $path_list = ResourcePathService::getResourcePath(['rid' => $info['id']]);
        $info['images'] = '';
        if ($path_list) {
            $path = '';
            foreach ($path_list as $v) {
                $path .= config('url.url') . $v['path'] . ',';
            }
            $info['images'] = rtrim($path, ',');
        }

        // 二级分类
        $info['cate_name'] = ResourceCateService::findResourceCateValue(['id' => $info['cids']]);

        // 省份
        $info['province'] = LocationService::getLocationValue(['location_id' => $info['province']]);

        // 城市
        $info['city'] = LocationService::getLocationValue(['location_id' => $info['city']]);

        // 地区
        $info['area'] = LocationService::getLocationValue(['location_id' => $info['area']]);

        return view('', ['info' => $info]);
    }

    /**
     * 添加推荐
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addRecommend()
    {
        $type = intval($this->request->param('type', 0));
        $id = intval($this->request->param('id', 0));
        if (!$type || !$id) {
            $this->error(adminJsonMsg(1001));
        }

        if (request()->isPost()) {
            $info = ResourceService::findResource(['id' => $id]);
            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            // 是否已推荐
            $recommend = ResourceRecommendService::findResourceRecommend(['rid' => $id, 'type' => $type]);
            if ($recommend) {
                $this->error(adminJsonMsg(1005));
            }

            $add_time = time();
            // 推荐周期为30天
            $end_time = strtotime('+30 days', $add_time);
            $res = ResourceRecommendService::createResourceRecommend([
                'rid' => $id,
                'type' => $type,
                'add_time' => $add_time,
                'end_time' => $end_time,
            ]);
            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            $this->success(adminJsonMsg(1004));
        }
    }

    /**
     * 取消社群推荐
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cancelRecommend()
    {
        if (request()->isPost()) {
            $id = intval($this->request->param('id', 0));
            $type = intval($this->request->param('type', 0));
            $where = ['rid' => $id, 'type' => $type];
//            var_dump($where);exit;
            $info = ResourceRecommendService::findResourceRecommend($where);

            if (!$info) {
                $this->error(adminJsonMsg(1002));
            }

            $res = ResourceRecommendService::delResourceRecommend($where);

            if (!$res) {
                $this->error(adminJsonMsg(1003));
            }

            // 重新执行推荐TimedTask.php
            TimedTask::recommended();

            $this->success(adminJsonMsg(1004));
        }
    }

    /**
     * 审核列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function check()
    {
        return $this->index([], 4);
    }

    /**
     * 推荐列表
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recommend()
    {
        return $this->index([], 3);
    }

    /**
     * 优质大群
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function high()
    {
        return $this->index(['r.is_high' => 1], 0);
    }

    /**
     * 直属服务商
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function service()
    {
        return $this->index(['r.is_service' => 1], 1);
    }

    /**
     * 官方伙伴
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function partner()
    {
        return $this->index(['r.is_partner' => 1], 2);
    }

    /**
     * 状态修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStatus()
    {
        $id = intval($this->request->param('id', 0));
        $source = intval($this->request->param('source', 0));
        $sort = intval($this->request->param('sort', 0));
        $field = trim($this->request->param('field', 'status'));
        if (!$id) {
            $this->error(adminJsonMsg(1001));
        }
        $where = ['id' => $id];
        $resource = ResourceService::findResource($where);
        if (!$resource) {
            $this->error(adminJsonMsg(1002));
        }

        // 删除/状态设置
        if (in_array($source, [2, 3])) {
            // 查询是否在推荐中
            $recommend = ResourceRecommendService::findResourceRecommend(['rid' => $id]);
            if ($recommend) {
                $this->error(adminJsonMsg(1007));
            }
        }

        // 1 排序字段  2删除 0其他
        switch ($source) {
            case 1:
                $changeFields = $sort;
                break;
            case 2:
                $changeFields = -1;
                break;
            default:
                $changeFields = $resource[$field] == 1 ? 0 : 1;
        }
//        var_dump($field,$sort,$changeFields,$where);exit;
        $result = ResourceService::updateResource([$field => $changeFields], $where);
        if (!$result) {
            $this->error(adminJsonMsg(1003));
        }

        $this->success(adminJsonMsg(1004));
    }

}